package com.bulletelc.apollopre.module.display.product.details;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.ProductDetailAll;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2017/12/26
 * desc  : TODO
 */

public class ProductDetailsPresenter extends BasePresenter<ProductDetailsContract.View> implements ProductDetailsContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void addCart(String json, String token) {
        addCartImp(json, token);
    }

    @Override
    public void buyNow(String json, String token) {
        buyNowImp(json, token);
    }

    @Override
    public void collect(String json) {
        postCollect(json);
    }

    @Override
    public void cancelCollect(int productId) {
        cancelCollectImp(productId);
    }

    /**
     * 添加到购物车
     *
     * @param json
     */
    private void addCartImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_CART_UPDATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseAddCart(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorAddCart(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 立即购买
     * @param json
     * @param token
     */
    private void buyNowImp(String json, String token) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_BUY_NOW)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(token))
                .params("eshop_id",1) //平台id默认1
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseDataBuyNow(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorBuyNow(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析立即购买返回的数据
     * @param response
     */
    private void parseDataBuyNow(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    Gson gson = new Gson();
                    OrderConfirmBean confirmBean=gson.fromJson(object.getJSONObject("data").toString(), OrderConfirmBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessBuyNow(confirmBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddCart(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailBuyNow(response.body().toString());
            }
        }
    }

    /**
     * 解析加入购物车返回数据
     *
     * @param response
     */
    private void parseAddCart(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                String code = metaObj.getString("code");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                    if (isViewAttached()) {
                        getView().onSuccessAddCart();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddCart(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailAddCart(response.body().toString());
            }
        }
    }

    /**
     * 添加收藏
     *
     * @param json
     */
    private void postCollect(String json) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_USER_COLLECTIONS_CREATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCollect(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCollect(response.body().toString());
                        }
                    }
                });
    }

    /**
     * 解析收藏数据
     *
     * @param response
     */
    private void parseCollect(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = obj.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessCollect();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCollect(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddCart("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCollect(response.body().toString());
            }
        }
    }

    /**
     * 取消收藏
     * @param productId
     */
    private void cancelCollectImp(int productId) {
        OkGo.<String>post(NetWorkPath.POST_USER_COLLECTION_CANCEL + "?id=" + productId)
                .headers(NetWorkPath.HEADER_KEY_AUTH,MyUtil.getAuthToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCancelCollect(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCancelCollect(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析取消收藏返回的数据
     * @param response
     */
    private void parseCancelCollect(Response<String> response) {
        if (response.isSuccessful()) {
            try {

                JSONObject object = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessCancelCollect();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCancelCollect(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCancelCollect("解析数据有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCancelCollect(response.body().toString());
            }
        }
    }

}
